<script setup lang="ts">
import { HomeWrap } from '@/components/HomeWrap'
import UserInfo from './components/UserInfo.vue'
import OrderInfo from '@/views/Home/Order/components/OrderInfo.vue'
import { ref, onMounted, onUnmounted } from 'vue'
import { userDetail } from '@/api/user/client'
import { getUserOrderPageList } from '@/api/order/client'
import { ElMessage, ElEmpty } from 'element-plus'
import Cookies from 'js-cookie'
import { orderStatusMap } from '@/constants/order'
import { useRouter } from 'vue-router'
import { Setting } from '@element-plus/icons-vue'

defineOptions({
  name: 'Order'
})

const router = useRouter()

// 用户信息
const userInfo = ref({
  name: '',
  phone: '',
  orderCount: 0,
  branch: ''
})

// 订单列表
const orderList = ref<any[]>([])
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(false)
const finished = ref(false)

// 跳转到设置页面
const goToSetting = () => {
  router.push({ name: 'UserSetting' })
}

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    // 从cookie中获取用户ID，实际项目中可能需要其他方式获取
    const token = Cookies.get('user_token')
    if (!token) {
      ElMessage.error('未登录')
      return
    }

    const res = await userDetail()
    if (res && res.data) {
      userInfo.value = {
        name: res.data.name || '',
        phone: res.data.phone || '',
        orderCount: res.data.orderCount || 0,
        branch: res.data.branch || ''
      }
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error('获取用户信息失败')
  }
}

// 获取订单列表
const fetchOrderList = async () => {
  if (loading.value || finished.value) return

  try {
    loading.value = true
    const params = {
      pageNum: pageNum.value,
      pageSize: pageSize.value
    }

    const res = await getUserOrderPageList(params)
    if (res && res.data && res.data.list) {
      // 根据实际返回的分页数据结构处理数据
      if (pageNum.value === 1) {
        orderList.value = res.data.list
      } else {
        orderList.value = [...orderList.value, ...res.data.list]
      }

      total.value = res.data.total
      pageNum.value++

      // 检查是否已经加载完所有数据
      if (orderList.value.length >= total.value) {
        finished.value = true
      }

      userInfo.value.orderCount = res.data.total
    }
  } catch (error) {
    console.error('获取订单列表失败:', error)
    ElMessage.error('获取订单列表失败')
  } finally {
    loading.value = false
  }
}

// 滚动到底部时加载更多
const onScrollToLower = () => {
  if (!loading.value && !finished.value) {
    fetchOrderList()
  }
}

// 格式化订单状态
const formatOrderStatus = (status: number) => {
  return orderStatusMap[status] || '未知状态'
}

// 处理滚动事件
let ticking = false
const handleScroll = () => {
  if (!ticking) {
    requestAnimationFrame(() => {
      const mainWrap = document.querySelector('.main-wrap')
      if (!mainWrap) return

      const { scrollTop, scrollHeight, clientHeight } = mainWrap
      // 当滚动到底部附近时触发加载更多
      if (scrollHeight - scrollTop - clientHeight < 20) {
        onScrollToLower()
      }
      ticking = false
    })
    ticking = true
  }
}

// 初始化
onMounted(() => {
  fetchUserInfo()
  fetchOrderList()

  // 添加滚动事件监听器
  const mainWrap = document.querySelector('.main-wrap')
  if (mainWrap) {
    mainWrap.addEventListener('scroll', handleScroll)
  }
})

// 组件销毁前移除事件监听器
onUnmounted(() => {
  const mainWrap = document.querySelector('.main-wrap')
  if (mainWrap) {
    mainWrap.removeEventListener('scroll', handleScroll)
  }
})
</script>

<template>
  <HomeWrap>
    <div class="header-container">
      <h2 class="page-title">个人中心</h2>
      <div class="setting-icon" @click="goToSetting">
        <el-icon :size="20"><Setting /></el-icon>
      </div>
    </div>
    <UserInfo
      :name="userInfo.name"
      :phone="userInfo.phone"
      :order-count="userInfo.orderCount"
      :branch="userInfo.branch"
    />

    <template v-if="orderList.length > 0">
      <OrderInfo
        v-for="order in orderList"
        :key="order.orderNo"
        :img="order.firstProductImage"
        :order-no="order.orderNo"
        :status="formatOrderStatus(order.orderStatus)"
        :order-time="order.createdAt"
        :quantity="order.totalQty"
      />

      <!-- 加载提示 -->
      <div v-if="loading" class="loading-text">加载中...</div>
      <div v-else-if="finished && orderList.length > 0" class="loading-text">没有更多了</div>
    </template>

    <template v-else>
      <el-empty v-if="!loading" description="订单为空，快去下单吧！" />
    </template>
  </HomeWrap>
</template>

<style scoped>
.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
}

.page-title {
  margin: 0;
  flex: 1;
}

.setting-icon {
  cursor: pointer;
  color: #409eff;
  padding: 8px;
}

.loading-text {
  text-align: center;
  padding: 16px;
  color: #999;
}
</style>
